package main.java.xyz.luxiaoxiang.framework.helper;

import xyz.luxiaoxiang.framework.annotation.Inject;
import xyz.luxiaoxiang.framework.util.ArrayUtil;
import xyz.luxiaoxiang.framework.util.CollectionUtil;
import xyz.luxiaoxiang.framework.util.ReflectionUtil;

import java.lang.reflect.Field;
import java.util.Map;

/**
 * 依赖助手类
 * Created by luxx on 2018/2/27 0027.
 */
public final class IocHelper {

    static {
        //获取所有的bean类 与bean实例之间的映射关系（bean map)
        Map<Class<?>, Object> beanMap = BeanHelper.getBeanMap();
        if (CollectionUtil.isNotEmpty(beanMap)) {
            //遍历 Bean Map
            for (Map.Entry<Class<?>, Object> beanEntry : beanMap.entrySet()) {
                //从 BeanMap 获取bean 类与bean 实例
                Class<?> beanClass = beanEntry.getKey();
                Object beanInstance = beanEntry.getValue();
                //获取 Bean 类意义的所有成员变量（bean field)
                Field[] beanFields = beanClass.getDeclaredFields();
                if (ArrayUtil.isNotEmpty(beanFields)) {
                    //遍历 Bean field
                    for (Field beanField : beanFields) {
                        //判断当前 Bean Field 是否带有 Inject 注解
                        if (beanField.isAnnotationPresent(Inject.class)) {
                            //在bean map 中获取bean field 对应的实例//todo
                            Class<?> beanFieldClass = beanField.getType();
                            Object beanFieldInstance = beanMap.get(beanFieldClass);
                            if (beanFieldInstance != null) {
                                //通过反射初始化BeanField 的值
                                ReflectionUtil.setField(beanInstance, beanField, beanFieldInstance);
                            }
                        }
                    }
                }
            }
        }
    }
}
